package cn.xxstudy.blog.service

import cn.xxstudy.blog.dao.CategoryRepository
import cn.xxstudy.blog.entity.Category
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.*
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.lang.Exception


/**
 * 作者：wuxinxi on 2020/11/25
 * 包名：cn.xxstudy.blog.service
 * TODO:一句话描述
 */
@Service
class CategoryService : ICategoryService {
    @Autowired
    private lateinit var categoryRepository: CategoryRepository

    override fun createCategory(category: Category): Category? {
        return categoryRepository.save(category)
    }

    override fun getCategoryById(id: Long): Category? = categoryRepository.getOne(id)

    override fun getCategoryByName(categoryName: String): Category? = categoryRepository.findCategoryByCategoryName(categoryName)

    /**
     * 分页获取
     */
    override fun listCategory(pageable: Pageable): Page<Category> {
        return categoryRepository.findAll(pageable)
    }

    override fun listCategory(): List<Category> {
        return categoryRepository.findAll()
    }

    /**
     * 排序后的所有分类类别 有bug
     */
    @Deprecated("No property size found for type Blog! Traversed path: Category.blogs.]")
    override fun listCategoryBySort(): List<Category> {
        val sort = Sort.by(Sort.Direction.DESC, "blogs.size")
        return categoryRepository.findAll(sort)
    }

    override fun listCategoryTop(size: Int): List<Category> {
        val sort = Sort.by(Sort.Direction.DESC, "blogs.size")
        val pageable = PageRequest.of(0, size, sort)
        return categoryRepository.findTop(pageable)
    }

    @Transactional
    override fun deleteById(id: Long): Boolean {
        return try {
            categoryRepository.deleteById(id)
            true
        } catch (e: Exception) {
            false
        }
    }

    @Transactional
    override fun deleteByName(categoryName: String): Boolean {
        return categoryRepository.deleteByCategoryName(categoryName) > 0
    }

    @Transactional
    override fun updateByName(categoryName: String, sourceCategory: Category): Boolean {
        val category = getCategoryByName(categoryName) ?: return false
        BeanUtils.copyProperties(sourceCategory, category)
        return try {
            categoryRepository.save(category)
            true
        } catch (e: Exception) {
            false
        }
    }

}